<?php
/**
 * tpAdmin [a web admin based ThinkPHP5]
 *
 * @author    yuan1994 <tianpian0805@gmail.com>
 * @link      http://tpadmin.yuan1994.com/
 * @copyright 2016 yuan1994 all rights reserved.
 * @license   http://www.apache.org/licenses/LICENSE-2.0
 */

namespace app\admin\controller;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Db;
use \think\File;

class Upload extends Base
{
    /**
     * 首页
     */
    public function index()
    {
        return $this->view->fetch();
    }

    /**
     * 文件上传
     */
    public function upload()
    {
        $file = $this->request->file('file');
        $path = ROOT_PATH . 'public/tmp/uploads/';
        $info = $file->move($path);
            if (!$info) {
            return ajax_return_error($file->getError());
        }
        $data = $this->request->root() . '/tmp/uploads/' . $info->getSaveName();
        $insert = [
            'cate'     => 3,
            'name'     => $data,
            'original' => $info->getInfo('name'),
            'domain'   => '',
            'type'     => $info->getInfo('type'),
            'size'     => $info->getInfo('size'),
            'mtime'    => time(),
        ];
        Db::name('File')->insert($insert);

        return ajax_return(['name' => $data]);
    }

    /**
     * 远程图片抓取
     */
    public function remote()
    {
        $url = $this->request->post('url');
        // validate
        $name = ROOT_PATH . 'public/tmp/uploads/' . get_random();
        $name = \File::downloadImage($url, $name);

        $ret = $this->request->root() . '/tmp/uploads/' . basename($name);

        return ajax_return(['url' => $ret], '抓取成功');
    }

    /**
     * 图片列表
     */
    public function listImage()
    {
        $page = $this->request->param('p', 1);
        if ($this->request->param('count')) {
            $ret['count'] = Db::name('File')->where('cate=3')->count();
        }
        $ret['list'] = Db::name('File')->where('cate=3')->field('id,name,original')->page($page, 10)->select();

        return ajax_return($ret);
    }

    /**
     * 轮播图片上传
     */
    public function img_upload(){
        $files = $_FILES;
        if (empty($files) || count($files) < 1)
        {
            return json_encode(['code' => 400135, 'msg' => 'FAULT']);
        }
        $dir = 'activity_img';
        $file = request()->file('activity_img');
        $info = $file->validate(['size' => 2*1024*1024, 'ext' => 'jpg,JPG,png,PNG'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $dir);

        if ($info)
        {
            $apk_path = 'uploads' . DS . $dir . DS . $info->getSaveName();
        }
        else
        {
            return json(['code' => 0, 'msg' => $file->getError()]);
        }
        $img_pre = $_SERVER['HTTP_HOST'] != 'admin.vipbuy360.com' ? 'http://'.$_SERVER['HTTP_HOST'] : config('api_host');
        $res_info = ['code' => 200, 'msg' => 'SUCCESS', 'data' => ['path' => str_replace("\\", "/", $apk_path), 'host_path' => $img_pre . '/' . str_replace("\\", "/", $apk_path)]];
        echo json_encode($res_info);
    }

    /**
     * 七牛云图片上传
     */
    public function upload_qiniu(){
        $files = $_FILES;
        if (empty($files) || count($files) < 1)
        {
            return json_encode(['code' => 0, 'msg' => '无图片文件']);
        }
        $file = request()->file('image');
        $filePath = $file->getRealPath();
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        // 上传到七牛后保存的文件名
        $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = config('ACCESSKEY');
        $secretKey = config('SECRETKEY');
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        // 要上传的空间
        $bucket = config('BUCKET');
        $domain = config('DOMAINImage');
        $token = $auth->uploadToken($bucket);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return json(["code"=>0,"msg"=>$err,"data"=>""]);
        } else {
            //返回图片的完整URL
            return json(["code"=>200,"msg"=>'success',"data"=>$ret]);
        }

    }
}